<template>
  <div class="flow">
    <!-- 员工信息卡片 -->
    <div class="formLook" :class="{ 'full-width': isFullWidth }">
      <div class="Resignation">
        <div class="employee-card">
          <div class="firstTitle" @click="$GoBack()">
            <div class="icon">
              <el-icon>
                <ArrowLeft />
              </el-icon>
            </div>
            <div class="topTitle">离职申请</div>
          </div>
          <el-divider />

          <div class="employee-avatar">
            <ImageComponent
              :src="userInfoForm.personPhoto"
              width="100px"
              height="100px"
              borderRadius="6px"
            />
          </div>

          <el-form label-width="100px" size="small" style="margin-left: 20px">
            <div class="section-title">
              <span>员工信息</span>
            </div>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="员工账号：">
                  <span>{{ userInfoForm.applicantPersonName }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="工号：">
                  <span>{{ userInfoForm.jobNumber }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="联系电话：">
                  <span>{{ userInfoForm.phoneNumber }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="工作邮箱：">
                  <span class="ellipsis-text">{{ userInfoForm.mail }}</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="岗位名称：">
                  <span>{{ userInfoForm.resignOldJobName }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="岗位性质：">
                  <span>{{ userInfoForm.resignBeforeJobNature }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="部门：">
                  <span>{{ userInfoForm.resignOldDeptName }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="职级：">
                  <span>{{ positionLevelText }}</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="直属领导：">
                  <span>{{ userInfoForm.directLeaderName }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="最高领导：">
                  <span>{{ userInfoForm.supremeLeaderName }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="入职日期：">
                  <span>{{ userInfoForm.joinTime }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="转正日期：">
                  <span>{{ userInfoForm.becomePassTime }}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <!-- 申请流程 -->
        <div class="application-form">
          <div class="procedure">
            <div class="procedure_title">申请流程</div>
          </div>
          <el-divider />

          <div style="margin-left: 20px">
            <el-form :model="userInfoForm" label-width="120px" size="small">
              <!-- 离职信息 -->
              <div class="section-title">
                <span>离职信息</span>
              </div>

              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="离职类型：">
                    <span>{{ getTransferTypeName.value }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="预计离职日期：">
                    <span>{{ userInfoForm.expectResignTime }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="离职原因简述：">
                    <span>{{ userInfoForm.resignSeason }}</span>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="离职交接人：">
                    <span>{{ userInfoForm.resignConnectPersonName }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="岗位名称：">
                    <span>{{ userInfoForm.resignJobName }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="部门：">
                    <span>{{ userInfoForm.resignDeptName }}</span>
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 其他信息 -->
              <div class="section-title">
                <span>其他信息</span>
              </div>

              <el-form-item label="备注：">
                <span>{{ userInfoForm.remark }}</span>
              </el-form-item>

              <el-form-item label="其他附件：">
                <attachment
                  v-if="
                    userInfoForm.saveTransferFileVos &&
                    userInfoForm.saveTransferFileVos != null
                  "
                  :employeeResignFileVoList="userInfoForm.saveTransferFileVos"
                >
                </attachment>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>

    <div class="flowtab_info" v-if="isFullWidth">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="流程过程" name="流程过程">
          <div class="flowProcess">
            <steps
              :flowableDataList="flowableDataList"
              @submit="handleSubmit"
              @close="$GoBack()"
              v-bind="route.query.examine == 1 ? { flowableBtns } : {}"
            >
            </steps>
          </div>
        </el-tab-pane>
        <el-tab-pane label="流程图" name="流程图">
          <bpmnViewer :flowData="flowDatas" :id="hightlightId" />
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import ImageComponent from "@/components/ImageComponent.vue";
import { useRouter } from "vue-router";
import { formatDate } from "@/utils/index.js";
import TitleComponent from "@/components/TitleComponent.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute } from "vue-router";
import { transferApi } from "@/api/employeeRelations/transferManagement.js";
import useUserStore from "@/store/modules/user.js";
import {
  flowableTodo,
  flowablePhoto,
  flowableRecord,
} from "@/api/flowableApi/flowableApi.js";
import bpmnViewer from "@/components/Process/viewer/index.vue";
import { seeFileView, getFileName } from "@/utils/fileView.js";
import steps from "@/components/step/index.vue";
import { applicationDetails } from "@/api/employeeRelations/separationManagement.js";
import attachment from "@/components/attachment.vue";
const router = useRouter();

const user = useUserStore().user;
const userInfoForm = reactive({
  applicantPersonName: "", //员工账号
  jobNumber: "", //工号
  phoneNumber: "", //联系电话
  mail: "", //工作邮箱
  resignOldJobName: "", //原岗位名称
  resignOldDeptName: "", //原部门
  resignBeforeJobNature: "", //岗位性质
  positionLevel: "", //职级
  directLeaderName: "", //直属领导
  supremeLeaderName: "", //最高领导
  joinTime: "", // 入职日期
  becomePassTime: "", //转正日期
  typeTransfer: "", //调岗类型
  applyDate: "", //申请日期

  nowDepartmentJobName: "", //调岗后岗位名称
  nowJobNature: "", //调岗后岗位性质
  nowDepartmentName: "", //调岗后部门
  nowPositionLevel: "", //调岗后职级
  leaderAfterTransferName: "", //调岗后直属领导
  leaderAfterHighName: "", //调岗后最高领导
  reasonTransfer: "", //调岗说明
  saveTransferFileVos: [], //附件

  resignType: "", //调动类型
  resignJobName: "", //离职岗位名称
  resignDeptName: "", //离职部门
  resignConnectPersonName: "", //离职交接人姓名
  remark: "", //备注
  resignSeason: "", //离职原因描述
  expectResignTime: "", //离职日期
});
const route = useRoute();
const { proxy } = getCurrentInstance();

const activeName = ref("流程过程");
// 岗位信息库弹窗
const flowDatas = ref({});
// 留痕数据
const flowableDataList = ref([]);
// 审核按钮
const flowableBtns = ref([]);
// 下一个审批数据
const flowableTodoData = ref([]);
const procInsId = ref("");
// 高亮节点id
const hightlightId = ref("");
const taskId = ref("");
const getTransferTypeName = ref("");

const query = computed(() => {
  let id = route.query ? Number(route.query.id) : "";
  return { id };
});
const { sys_dimission_type } = proxy.useDict("sys_dimission_type");
const normalizedTransferType = computed(() => {
  return sys_dimission_type.value.map((item) => ({
    label: item.label,
    value: Number(item.value), // 确保为数字类型
  }));
});

onMounted(() => {
  getDetails();
});
const isFullWidth = computed(() => {
  return route.query.workFlow == "1";
});

function getDetails() {
  const employeeResignId = query.value.id;

  applicationDetails(employeeResignId).then((res) => {
    if (res.data) {
      // 使用扩展运算符简化对象赋值
      Object.assign(userInfoForm, {
        ...res.data,
        typeTransfer: res.data.typeTransfer,
        directLeaderName: res.data.directLeaderName,
        joinTime: formatDate(res.data.joinTime).dates,
        becomePassTime: formatDate(res.data.becomePassTime).dates,
        applyDate: formatDate(res.data.applyDate).dates,
        saveTransferFileVos: res.data.employeeResignFileVoList,
      });

      // 处理流程实例 ID
      if (res.data.processId) {
        procInsId.value = res.data.processId;
        init(res.data.processId);
      }

      // 处理离职类型显示
      getTransferTypeName.value = computed(() => {
        if (userInfoForm.resignType == null) {
          return "";
        }
        const transferType = normalizedTransferType.value.find(
          (item) => item.value == userInfoForm.resignType
        );
        return transferType ? transferType.label : "";
      });
      console.log(getTransferTypeName.value, "getTransferTypeName");
    }
  });
}

// 计算属性：动态显示按钮名称
const getButtonName = (item) => {
  if (item.btnName === "通过审批") return "通过";
  if (item.btnName === "退回修改") return "驳回";
  return item.btnName; // 如果不符合条件，直接返回原始名称
};
const init = async (processId) => {
  const params = {
    owner: user.userId,
    role: user.userId,
    flowKey: "EMPLOYEE_RESIGN_MANAGEMENT",
  };

  try {
    // 留痕
    const recordRes = await flowableRecord({
      procInsId: processId,
      flowKey: "EMPLOYEE_RESIGN_MANAGEMENT",
    });

    if (recordRes.data.flowList.length > 0) {
      // 简化排序逻辑
      recordRes.data.flowList.sort((a, b) => b.taskId - a.taskId);
      flowableDataList.value = recordRes.data.flowList;

      if (flowableDataList.value.length > 0) {
        nextTick(() => {
          const steps = document.querySelectorAll(".el-step__icon-inner");
          steps.forEach((item, index) => {
            item.innerHTML = steps.length - index;
          });
        });
      }
    }

    // 流程审批按钮
    const todoRes = await flowableTodo(processId, params);
    if (todoRes.data.length > 0) {
      // 审批
      flowableBtns.value = JSON.parse(todoRes.data[0].description)[0].btns;
      flowableTodoData.value = todoRes.data[0];
      taskId.value = todoRes.data[0].taskId;
    }
  } catch (error) {
    console.error(error);
  }
};
const positionLevelText = computed(() => {
  const positionLevelMap = {
    0: "初级",
    1: "中级",
    2: "高级",
  };
  return positionLevelMap[userInfoForm.positionLevel] || "";
});

const handleClick = (tab) => {
  if (tab.props.name === "流程图") {
    flowablePhoto({
      procInsId: procInsId.value,
      flowKey: "EMPLOYEE_RESIGN_MANAGEMENT", // 后续需修改为调动管理flowKey
    })
      .then((res) => {
        if (res.data) {
          flowDatas.value = res.data;
          if (res.data.nodeData && res.data.nodeData.length > 0) {
            hightlightId.value =
              res.data.nodeData[res.data.nodeData.length - 1].key;
          }
        }
      })
      .catch((error) => {
        console.error("获取流程图数据失败:", error);
        ElMessage.error("获取流程图数据失败");
      });
  }
};
const handleSubmit = (parameter) => {
  const { type: item, comment } = parameter;
  const commonData = {
    accessory: [],
    accessoryList: [],
    agencyId: item.agencyId || "",
    agencyNextrole: "",
    assignee: user.userId, // 当前人
    auditOpinion: comment, // 审批意见
    auditTime: formatDate(new Date()).allDate, // 当前时间
    auditUserName: user.userName, // 审批人 userName
    beAssigner: "",
    beAssignerName: "",
    beAssignerRole: "",
    buId: user.dept.deptId, // user buid
    id: query.value.id, // 按钮id
    messageId: "",
    nextBuCode: "",
    otherFiles: [],
    processInstanceId: flowableTodoData.value.processInstanceId,
    taskId: flowableTodoData.value.taskId,
    flowKey: "EMPLOYEE_RESIGN_MANAGEMENT",
  };

  const data = {
    ...commonData,
    btnName: item.btnName, // 按钮名
    status: item.status,
    vars: item.btnValue || "",
  };

  if (item.btnName === "保存") {
    handleSave(data, item);
  } else {
    handleApproval(data, item);
  }
};

const handleSave = (data, item) => {
  console.log(data, "保存的data");
  console.log(item, "保存的item");
  approveGoto(data, item);
};

const handleApproval = (data, item) => {
  ElMessageBox.confirm(`是否要${item.btnName}这条用人需求申请审批?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      approveGoto(data, item);
    })
    .catch(() => {
      ElMessage.info("已取消");
    });
};

const approveGoto = (data, item) => {
  transferApi(data, item.btnUrl)
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success(`${item.btnName}成功`);

        proxy.$GoBack();
      } else {
        ElMessage.error(`${item.btnName}失败`);
      }
    })
    .catch((error) => {
      console.error("审批请求失败:", error);
      ElMessage.error("请求失败，请重试");
    });
};
</script>

<style scoped>
.Resignation {
  background: #f1f1f1;
  border-radius: 11px;
}
.back-button {
  margin-bottom: 20px;
}

.employee-card {
  background-color: #fff;
  border-radius: 8px;
  /* box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); */
  /* padding: 10px; */
  margin-bottom: 10px;
}

.employee-avatar {
  text-align: left;
  margin-top: 10px;
}

.application-form {
  background-color: #fff;
  border-radius: 8px;
  /* box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); */
}
.button-group {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: bold;
  color: #606266;
}

:deep(.el-textarea__inner) {
  resize: none;
}

.section-title {
  font-size: 15px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-left: 10px;
  border-left: 0px solid #409eff;
  color: #16191d;
}
.position-container {
  display: flex;
}

.contianer-left {
  width: 48%;
}
.contianer-right {
  width: 48%;
}

.transfer-info-container {
  margin-top: 20px;
}

.section-title {
  font-weight: bold;
  margin: 20px 0 15px 0;
  padding-left: 15px;
  position: relative;
}

.section-title:before {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 4px;
  background-color: #409eff;
  border-radius: 2px;
}

.el-form-item {
  margin-bottom: 15px;
}

.original-info {
  min-width: 180px;
  color: #606266;
}

.arrow {
  margin: 0 10px;
  color: #409eff;
}

.target-info {
  display: flex;
  color: #409eff;
}
span {
  width: 80%; /* 设定容器的宽度 */
  white-space: normal; /* 允许文本换行 */
}

.info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.topTitle {
  color: #16181d;
  font-size: 14px;
}
.procedure {
  height: 40px;
  line-height: 40px;
  margin-left: 10px;
  color: #16181d;
  font-size: 14px;
}
</style>
